﻿using Zbk_VoteSys.Models;
using Zbk_VoteSys.Models.Database;
using Zbk_VoteSys.Service;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;

namespace Zbk_VoteSys.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class UserController : ControllerBase
    {

        private readonly Zbk_VoteSysContext _db;
        private readonly IJWTService _jwtservice;

        public UserController(Zbk_VoteSysContext db, IJWTService jwtservice)
        {
            _db = db;
            _jwtservice = jwtservice;
        }

        //从控制器的构造函数取服务


        /// <summary>
        /// 注册接口（用户使用手机号码，密码进行注册，密码需要二次确认）
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public string Register(RegisterRequest request)
        {
            //两次密码是否一致
            if (request.Password != request.CirPassword)
                return "密码输入不一致";
            if (_db.Users.Any(x => x.Email == request.Email))
                return "用户已存在";

            ////数字随机字符串
            //var salt = new Random().Next(1000, 10000);

            ////加入一步  把明文密码  转换成 md5字符串
            //var md5 = MD5Helper.MD5Encrypt32(request.Password + salt);

            //3、添加用户到数据库
            var user = new User
            {
                CreateTime = DateTime.Now,
                Email = request.Email,
                Password = request.Password
                //Password = md5,
                //Salt = salt.ToString()
            };
            _db.Users.Add(user);
            //保存更改
            var row = _db.SaveChanges();
            if (row > 0)
                return "注册成功";
            return "注册失败";
        }

        /// <summary>
        /// 登录接口 用户使用手机号码，密码进行登录，登录后可访问需要授权的页面）
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public string Login(LoginRequest request)
        {
            //1、用账号（手机号码）查询用户
            var user = _db.Users.FirstOrDefault(x => x.Email == request.Email);
            //2、判断用户是否存在
            if (user == null)
                return "用户不存在";

            //var md5 = MD5Helper.MD5Encrypt32(request.Password + user.Salt);

            if (user.Password != request.Password)
                return "密码不正确";
            //4、创建token
            return _jwtservice.CreateToken(user.UserId.ToString(), user.Email);
        }
    }
}
